package com.ybbase.framework.advice;

import com.ybbase.framework.base.model.ResponseBean;
import lombok.NoArgsConstructor;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常类
 *
 * @author chengang
 * @date 2019/9/7 9:48 上午
 * @since 4.0
 */
@RestControllerAdvice
@NoArgsConstructor
public class MetException extends Exception {

    public MetException(String message) {
        super(message);
    }

    /**
     * 捕捉shiro的异常
     *
     * @param e ShiroException
     * @return ResponseBean
     * @since 4.0
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseBean handle401(ShiroException e) {
        return new ResponseBean(401, e.getMessage());
    }

    /**
     * 捕捉UnauthorizedException
     *
     * @return ResponseBean
     * @since 4.0
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseBean handle401() {
        return new ResponseBean(401, "Unauthorized");
    }

    /**
     * 捕捉其他所有异常
     *
     * @param request http请求
     * @param ex      Throwable
     * @return ResponseBean
     * @since 4.0
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseBean globalException(HttpServletRequest request, Throwable ex) {
        return new ResponseBean(getStatus(request).value(), ex.getMessage());
    }

    /**
     * 获取status_code
     *
     * @param request http请求
     * @return HttpStatus
     * @since 4.0
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
